<?php
/**
 * File to handle all API requests
 * Accepts GET and POST
 * 
 * Each request will be identified by TAG
 * Response will be JSON data
 */
require dirname(__FILE__) . '/include/KLogger.php';
$log   = KLogger::instance(dirname(__FILE__) . '/log', KLogger::DEBUG);
$log->logInfo('Teste log no index');
  /**
 * check for POST request 
 */
if (isset($_POST['tag']) && $_POST['tag'] != '') {
    // get tag
    $tag = $_POST['tag'];
 
    // include db handler
    require_once 'include/DB_Functions.php';
    $db = new DB_Functions();
 
    // response Array
    $response = array("tag" => $tag, "success" => 0, "error" => 0);
 
    // check for tag type
    if ($tag == 'login') {
        // Request type is check Login
        $email = $_POST['email'];
        $password = $_POST['password'];
 
        // check for user
        $user = $db->getUserByEmailAndPassword($email, $password);
        if ($user != false) {
            // user found
            // echo json with success = 1
            $response["success"] = 1;
            //$response["uid"] = $user["unique_id"];
            $response["user"]["id"] = $user["user_id"];
            $response["user"]["username"] = $user["username"];
            $response["user"]["email"] = $user["email"];
            //$response["user"]["created_at"] = $user["created_at"];
            //$response["user"]["updated_at"] = $user["updated_at"];
            echo json_encode($response);
        } else {
            // user not found
            // echo json with error = 1
            $response["error"] = 1;
            $response["error_msg"] = "Email ou senha incorretos";
            echo json_encode($response);
        }
    } else if ($tag == 'register') {
    	$log->logInfo('tag : ', $tag);
        // Request type is Register new user
        $fullname = $_POST['fullname'];
        $email = $_POST['email'];
        $password = $_POST['password'];
        $nickname = $_POST['nickname'];
 
        // check if user is already existed
        if ($db->isUserExisted($email)) {
            // user is already existed - error response
            $response["error"] = 2;
            $response["error_msg"] = "Usuário já cadastrado";
            echo json_encode($response);
        } else {
            // store user
            $user = $db->storeUser($fullname, $email, $password, $nickname);
            $log->logInfo('user retornado do storeUser: ', $user);
            if ($user) {
            	$log->logInfo('entrou no if de verificaçao do user. user: ', $user);
                // user stored successfully
                $response["success"] = 1;
                //$response["uid"] = $user["unique_id"];
                $response["user"]["id"] = $user["user_id"];
                $response["user"]["fullname"] = $user["username"];
                $response["user"]["email"] = $user["email"];
                //$response["user"]["created_at"] = $user["created_at"];
                //$response["user"]["updated_at"] = $user["updated_at"];
                echo json_encode($response);
            } else {
                // user failed to store
                $response["error"] = 1;
                $response["error_msg"] = "Ocorreu um erro";
                echo json_encode($response);
            }
        }
        
    } else if ($tag == 'initial_info') {
    	$log->logInfo('tag : ', $tag);
        // Request type is Register new user
    	$id = $_POST['id'];
    	$email = $_POST['email'];
        $sex = $_POST['sex'];
        $weight = $_POST['weight'];
        $height = $_POST['height'];
        $dateBirthday = $_POST['dateBirthday'];
        
//         $weight = str_replace(".",",",$weight);
//         $height = str_replace(".",",",$height);
 
        // check if user is already existed
        if (!($db->isUserExisted($email))) {
        	$log->logInfo('email não encontrado: ', $email);
            // user is already existed - error response
            $response["error"] = 2;
            $response["error_msg"] = "Usuário não cadastrado";
            echo json_encode($response);
        } else {
            // store user
            //$user_info = $db->updateInitialInfoUser($email, $sex, $weight, $height, $dateBirthday);
        	$user_info = $db->updateInitialInfoUser($email, $sex, $weight, $height, $dateBirthday, $id);
            $log->logInfo('user retornado do updateInitialInfoUser: ', $user_info);
            if ($user_info) {
                //stored successfully
                $response["success"] = 1;
                //TODO: implementar. ver todo dentro de updateInitialInfoUser.
                $response["user"]["weight"] = $user_info["weight"];
                $response["user"]["height"] = $user_info["height"];
                echo json_encode($response);
            } else {
                // user failed to store
                $response["error"] = 1;
                $response["error_msg"] = "Ocorreu um erro";
                echo json_encode($response);
            }
        }
    } else {
        echo "Invalid Request";
    }
} else {
    echo "Access Denied";
}
?>